<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>btn</button>

    <script>
      const btn = document.querySelector("button");

      function fn(e) {
        console.log(123, this, e);
      }

      // const fn = () => {
      //   console.log(123, this);
      // };

      // let timer;
      // 要封装的防抖函数
      // 使用了闭包，解决的是全局变量，函数自执行的问题
      const debounce = (func, time) => {
        let timer;
        return function () {
          const _this = this;
          const arg = arguments;
          if (timer) {
            clearTimeout(timer);
          }
          timer = setTimeout(function () {
            func.apply(_this, arg);
          }, time);
        };
      };

      btn.onclick = debounce(fn, 1000);
      // btn.onclick = fn;
    </script>
  </body>
</html>
